using System;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

using Actions;
using Actions.Security;
using Actions.Connectors;

namespace Actions.Usecases
{
	/// <summary>
	/// Description of UsecaseSet.
	/// </summary>
	public class UsecaseSet
	{
		private Assembly	_item = null;
        private string		_title;
		private bool		_enable;
        private bool        _public;
	    private string      _regExp = "UC([a-zA-Z0-9]{1,128})";		
		
		public string		itemName
		{
			get
			{
				return _item.FullName;	
			}
		}	
		public string		title
		{
			get
			{
				return _title;	
			}
		}	
		public bool   		isPublic
		{
		   get
		   {
		        return _public;
		   }
		}
			
		public UsecaseSet(string assemblyName, bool mustBeLoaded, bool isPublic, 
			string title)
		{
			_enable = false;
			_public = false;
			_title = title;
			
			try {
				if(mustBeLoaded) {
					_item = Assembly.Load(assemblyName);
				} else {
					_item = Assembly.GetExecutingAssembly();
				}
				if(_item != null) {
				   _enable = true;
				   _public = isPublic;
				} 
			} catch(Exception e) {
				Manager.i.error("UsecaseSet", e);
			}
		}
		
		public bool execute(ref IConnector c, SecurityAgent sa) 
		{
			if(!_enable) return false;
			
			// Dirty hack: some modules provide itself AAA 
			string typeName = "";

			if(_public) {
	      		typeName = "Actions.Usecases." + sa.requestedUsecase.name;			
			} else {
	      		typeName = "Actions.Usecases." + sa.currentUsecase.name;
			}

			Type t = _item.GetType(typeName, false);
			if (typeof (IUsecase).IsAssignableFrom(t)) {
				IUsecase uc = (IUsecase) Activator.CreateInstance(t);
				try {
					uc.execute(ref c, sa);
                    return true; 
				} catch(Exception e) {
					Manager.i.error("UsecaseSet", e);
				}
			} 
			return false;
		}	
      
        public ArrayList getUsecasesList()
        {
           ArrayList res = new ArrayList();
           
           if(!_enable || _public) return res;
           foreach(Type ti in _item.GetTypes()) {
              if(Regex.IsMatch(ti.Name, _regExp)) {
                 string name = ti.Name.Substring(2);
                 res.Add(name);
              }
           }
           return res;
        }		

        public string getUsecasesListXML()
        {
           string s = "";	
           
           if(!_enable || _public) return s;
     
           s += "<usecaseset title='" + _title + "'>";
           foreach(Type ti in _item.GetTypes()) {
              if(Regex.IsMatch(ti.Name, _regExp)) {
                 string name = ti.Name.Substring(2);
                 s += "<usecase type='" + ti.Name + "'>" +  name + "</usecase>";
              }
           }
           s += "</usecaseset>";

           return s;
        }		
	}
}
